package com.gnerv.sylvanas.framework.core.tools;

import lombok.extern.slf4j.Slf4j;

/**
 * 执行时间工具
 */
@Slf4j
public class TimeTrackerTools implements AutoCloseable {

    private final String operation;
    private final long startTime;

    private TimeTrackerTools(String operation) {
        this.operation = operation;
        this.startTime = System.currentTimeMillis();
    }

    public static <T> T track(String operation, ThrowableSupplier<T> execution) throws Throwable {
        try (TimeTrackerTools ignored = new TimeTrackerTools(operation)) {
            return execution.get();
        }
    }

    @FunctionalInterface
    public interface ThrowableSupplier<T> {
        T get() throws Throwable;
    }

    @Override
    public void close() {
        long timeElapsed = (System.currentTimeMillis() - startTime);
        log.info("{} {} ms", operation, timeElapsed);
    }
}
